
layui.define(['table', 'form'], function(exports){
	  var $ = layui.$
	  ,table = layui.table
	  ,setter = layui.setter
	  ,common = layui.common
	  ,form = layui.form;
	  var parentJson = {};
	  var obj = {
			setParentJson: function setParentJson(json){
				parentJson = json;
		 	} 
	  }
	  var colsArr;
	  var tableTitle;
	  var tableField; //表头字段
	  var tableSearch = [];//全局搜索条件
	  var tableHead;//表头字段
	  $.ajax({
	      url: setter.host+'/adminmanager/user/getSelectHead'
	      ,type:'get'
	      ,dataType:'json'
	      ,success: function(res){
	        //请求成功后
	    	if(res.status == setter.response.statusCode.status_Success){
		      	  loadTable(res.data.field);
	        }else{
	        	window.location.href = setter.host+'/error/toNoPower?msg='+res.msg;
	        }
	      }
	    });
	  $('.layui-btn').on('click', function(){
  	    var type = $(this).data('type');
  	    active[type] ? active[type].call(this) : '';
  	  });
	  function loadTable(header){
		  colsArr = [
	  				{type: 'checkbox', fixed: 'left'},
	  	            {field: 'userId', title: '用户号',sort:false,align:'center'},
	  	            {field: 'username', title: '用户名',align:'center',sort:false},
 					{field: 'name', title: '姓名',align:'center',sort:false},
	  	            {field: 'phone', title: '手机号',align:'center',sort:false},
	  	            {field: 'password', title: '密码',align:'center',sort:false}
	  	        ];
			layui.each(colsArr,function(inx,val){
				tableHead += val.hasOwnProperty('field')?val.field:'-';
				tableHead += ',';
				tableTitle += val.hasOwnProperty('title')?(val.hide?'':val.title+','):',';
				tableField += val.hasOwnProperty('field')?(val.hide?'':val.field+','):',';
		   	})
		   	//tableHead是获取表字段
	   		tableHead = tableHead.substring(tableHead.indexOf(',')+1,tableHead.length-1);
			//导出时需要用到标题
			tableTitle = tableTitle.substring(tableTitle.indexOf(',')+1,tableTitle.length-1);
			//导出需要用到实际导出的字段
			tableField = tableField.substring(tableField.indexOf(',')+1,tableField.length-1);
			
		  //用户管理
		  table.render({
		    elem: '#LAY-user-manage'
		    ,url: setter.host + '/adminmanager/user/getpassword' 
		    ,cols: [colsArr]
		    //,toolbar: 'true'
			//,defaultToolbar: ['print']
		  	,method:'post'
		  	,contentType:'application/json; charset=utf-8'
		  	,where:{'headField':tableHead}
		    ,page: true
		    ,groups:2
		    ,limit: 15
		    ,limits:[15,30,50]
		    ,height: 'full-60'
	    	,text: {
	    	    none: '暂无相关数据' 
			}
			,done:function () {
				delete this.where; 
			}
		  });
	  }
	$('body').on('click', '*[imgHref]', function(){
		 	var imgUrl =  $(this).attr('src');
		  	getImageWidth(imgUrl, function(w, h){
		    w = h > 860? w/h*860: w
		    h = h > 860? 860: h
		    parent.layer.open({
		        type: 1,
		        title: false,
		        offset: 'auto',
		        area: [ w+'px', h+'px' ],
		        shadeClose: true,
		        content: '<div><img style="max-width: 100%;max-height: 100%" src="'+imgUrl+'"></div>'
		    });
		  });
	})
	//事件
	  var active = {
	    edit: function(){
	      var checkStatus = table.checkStatus('LAY-user-manage')
  	      ,checkData = checkStatus.data; 
  	      if(checkData.length === 0){
  	        return layer.msg('请选择数据');
  	      }
  	      if(checkData.length > 1){
    	        return layer.msg('只能编辑一行数据');
    	  }

		  layer.prompt({
				formType: 1
				,title: '敏感操作，请验证口令'
			}, function(value, index){
				console.log(checkData);
				console.log(checkData.userId);
				console.log(checkData.username);
				var command = layui.sessionData('layuiSession').command;
				if(value == command){
					layer.close(index);
					layer.confirm('确定重置吗？', function(index_confirm) {
						layer.close(index_confirm);
						layui.admin.req({
			        	    url: setter.host+'/adminmanager/user/reset_password'
			        	    ,type:'post'
			        	    ,dataType:'json'
			        	    ,contentType: "application/json; charset=utf-8"
			        	    ,data:JSON.stringify({"userId":checkData[0].userId,"username":checkData[0].username}) 
			        	    ,done: function(res){
			        	    	//请求成功后
			        	    	if(res.status == setter.response.statusCode.status_Success){
									table.reload('LAY-genius-table'); 
									layer.msg(res.msg);
								}else{
									layer.msg(res.msg);
								}
			        	    }
						});
					});
				}else{
					layer.msg('口令错误');
				}
			});
  	      /*checkData[0].bakUrl = setter.host+'/adminmanager/user/photo_select';
  	      layui.common.postUrl(checkData[0],setter.host+'/adminmanager/user/photo_edit');*/
  	  	}  
	  };
	  //监听排序工具条
	  table.on('sort(LAY-user-manage)', function(obj){
		 
		  //尽管我们的 table 自带排序功能，但并没有请求服务端。
		  //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
		  table.reload('LAY-user-manage', {
		    initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。
		    ,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
		      ascField: obj.field //排序字段
		      ,asc: obj.type //排序方式
		      ,headField:tableHead //表头字段
		      ,search: tableSearch //查询字段
		    }
		  });
	  });
	  table.on('tool(LAY-user-manage)', function(obj){
			 obj.data.bakUrl = setter.host+'/adminmanager/user/toSelect';
			 if(obj.event=='lookUp'){
				 layui.common.postUrl(obj.data,setter.host+'/adminmanager/user/toEdit');
			 }
	  });
	  
	  //监听搜索
	  form.on('submit(LAY-user-normal-search)', function(data){
		tableSearch = {};
		if(data.field.whereValue != ''){
			tableSearch.name = data.field.whereValue;	
		}
		parentJson.search=tableSearch;
	    table.reload('LAY-user-manage', {
	    	where: parentJson
	    });
	  });
	  //监听搜索
	  form.on('submit(LAY-user-gread-search)', function(data){
	    layer.msg('暂不支持');
	  });
	  	function getImageWidth(url, callback) {
		var img = new Image();
	  	img.src = url;
	  	// 如果图片被缓存，则直接返回缓存数据
	  	if (img.complete) {
	    	callback(img.width, img.height);
	  	} else {
	    	img.onload = function () {
	      		callback(img.width, img.height);
	    	}
		} 
	}
	  exports('select', {})
});